package com.example.prom.dangwen.y2023.thread;


public class ThreadTest {
    public static void main(String[] args) {
        Thread a = new MyThread("A", 0, 10);
        Thread b = new MyThread("B", 1, 10);
        Thread c = new MyThread("C", 2, 10);
        a.start();
        b.start();
        c.start();
    }
}


class MyThread extends Thread{

    // 定义一个共享锁,静态变量所有实例共享
    private static final Object lock = new Object();

    // 配合线程编号控制打印顺序
    private static int counter = 0;

    private final int value; // 线程编号
    private final String symbol; // 打印符号
    private final int total; // 打印次数

    public MyThread(String symbol, int value, int total){
        this.symbol = symbol;
        this.value = value;
        this.total = total;
    }

    @Override
    public void run() {
        for (int i = 0; i < total; i++) {
            synchronized (lock){
                // 0, 1, 2 -> value
                while (counter % 3 != value){
                    try {
                        // wait会释放锁
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("symbol:"+symbol+",value:"+value+", threadName:" + Thread.currentThread().getName());
                counter++;
                // notify不会释放锁
                lock.notifyAll();
                System.out.println("counter:"+counter);
            }
        }
    }
}
